﻿@using si.caha.Model;
@using si.caha.Repository;

@{
    var item = new Item();
    if (PageData["item"] != null)
    {
        item = PageData["item"];
    }
    var dataContext = new DataContext();
    var categoryRepository = new CategoryRepository(dataContext);
    var categories = categoryRepository.GetAll();
    var disabledSubmitAttribute = "";
    if (categories.Count == 0)
    {
        disabledSubmitAttribute = "disabled";
    }
    
    if (IsPost)
    {
        // when in create mode
        if (item.ItemId == 0)
        {
            var itemId = Request.Form["itemId"].IsInt() ? Request.Form["itemId"].AsInt() : 0;
            if (itemId > 0)
            {
                var itemRepository = new ItemRepository(dataContext);
                item = itemRepository.Get(itemId);
            }
        }
        // this have to be, if not some dummy file is saved!
        if (Request.Files.Count > 0 && Request.Files[0].FileName.Length > 0 && item.ItemId > 0)
        {
            int numFiles = Request.Files.Count;
            for (int i = 0; i < numFiles; i++)
            {
                var uploadedFile = Request.Files[i];
                var relativeFilePath = "~/Admin/Items/Images/" + item.ItemId + "-" + uploadedFile.FileName.Replace(" ", "-");
                var absoluteFilePath = Server.MapPath(relativeFilePath);
                uploadedFile.SaveAs(absoluteFilePath);
                
                var image = new Image();
                image.ItemId = item.ItemId;
                image.Path = relativeFilePath;
                
                var imageRepository = new ImageRepository(dataContext);
                imageRepository.Save(image);
            }
        }
    }
}
<script>
    $(function(){
        // http://docs.jquery.com/UI/Tabs
        $('#tabs').tabs();
        
        // ============================ Item ============================ //
        var newItem = $('#itemId').val() == 0;
        if (newItem) {
            // hide images tab if item isn't created yet
            $('#imagesTab').hide();
            $('#imagesTabLink').hide();
            $('#submitItem').html('Create');
        }
        else {
            $('#submitItem').html('Save');
        }
        
        $('form#itemForm').change(function(){
            $('#submitItem').removeAttr('disabled');
            if (newItem) {
                $('#submitItem').html('Create');
            }
            else {
                $('#submitItem').html('Save');
            }
        });
        
        $('form#itemForm').submit(function(){
            $('#titleError').html('');
            $('#priceError').html('');
            $.post('/Admin/Items/partial/saveItem.cshtml', $('#itemForm').serialize(),
                function(data){
                    $('#titleError').html(data.Title);
                    $('#priceError').html(data.Price);
                    
                    if (data.Message) {
                        $('#imagesTab').show();
                        $('#imagesTabLink').show();
                        $('#imageForm>#itemId').attr('value', data.ItemId);
                        $('#submitItem').html(data.Message);
                        $('#submitItem').attr('disabled', 'disabled');
                    }
                },  
            'json');
                
            return false;
        });
        
        
        // ============================ Images ============================ //
        $('input#submitImage').hide();
        $('form#itemImageForm').change(function() {
            $('input#submitImage').show();
        });
        
        $('form#itemImageForm').submit(function(){
            $.post('/Admin/Items/partial/saveImage.cshtml', $('#itemImageForm').serialize(), 
                function(){
                    $('input#submitImage').hide();
            });
                    
            return false;
        });
    });
</script>
@if(disabledSubmitAttribute == "disabled")
{
    <span>You can't create new item this time, because you have no categories yet</span>
    <a href="@Href("~/Admin/Categories/Create")">Create category first</a>
}
<div id="tabs">
    <ul>
        <li><a href="#descriptionTab"><span>Item description</span></a></li>
        <li id="imagesTabLink"><a href="#imagesTab"><span>Item images</span></a></li>
    </ul>
    <div id="descriptionTab">
        <form id="itemForm" method="post">
            <div>
                <label for="title">Title:</label>
                <input id="title" name="title" type="text" placeholder="Title" value="@item.Title" />
                <span id="titleError"></span>
            </div>
            <input type="hidden" id="itemId" name="itemId" value="@item.ItemId" />
            <div>
                <label for="description">Description:</label><br>
                <textarea id="description" name="description" rows="10" cols="50">@item.Description</textarea>
            </div>
            <div>
                <label for="category">Category:</label>
                <select id="category" name="category">
                    @foreach (var category in categories)
                    {
                        var selectedAttribute = "";
                        var selectedCategoryId = 0;
                        
                        if (item.Category != null)
                        {
                            selectedCategoryId = item.Category.CategoryId;
                        }
                            
                        if (category.CategoryId == selectedCategoryId)
                        {
                            selectedAttribute = "selected";
                        }
                        <option value="@category.CategoryId" @selectedAttribute>@category.Title</option>
                    }
                </select>
            </div>
            <div>
                <label for="price">Price:</label>
                <input id="price" name="price" placeholder="Price" type="number" value="@item.Price" />
                <span id="priceError"></span>
            </div>      
            <div>
                <button type="submit" id="submitItem" @disabledSubmitAttribute></button>
            </div>
        </form>
    </div>
    <div id="imagesTab">
        @if (item.Images != null)
        {
            <form id="itemImageForm" method="post">
                @foreach (var image in item.Images)
                {
                    <p>@image.Path</p>
                    <a href="@Href("~/Admin/Items/Images/Delete/" + image.ImageId + "/?ReturnUrl=/Admin/Items/Edit/" + item.ItemId)"> 
                        <img src="@Href(@image.Path)" height="100px" width="100px" />
                    </a>
                    var checkedAttribute = image.FrontImage ? "checked" : "";
                    <label for="frontImage">Front image:</label>
                    <input type="radio" id="frontImage" name="frontImage" value="@image.ImageId" @checkedAttribute />
                }
                <br/>
                <input type="submit" id="submitImage" value="Save" />
            </form>
        }
        <div>
            <form id="imageForm" method="post" enctype="multipart/form-data" action="#imagesTab">
                <input type="hidden" id="itemId" name="itemId" />
                @FileUpload.GetHtml(
                    initialNumberOfFiles: 1,
                    allowMoreFilesToBeAdded: true,
                    addText: "Add another file",
                    includeFormTag: false)
                <button type="submit" id="submitImageData">Upload</button>
            </form>
        </div>
    </div>
</div>